import React from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { requiresAuth, getRouteConfig } from '@/router/routeConfig';

/**
 * 受保护的路由组件
 * 用于包装需要登录才能访问的页面
 */
const ProtectedRoute = ({ children, fallback = null, requireAuth = true }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { isLogin, loading } = useSelector(state => state.user);
  const currentPath = location.pathname;

  // 获取路由配置
  const routeConfig = getRouteConfig(currentPath);

  // 如果当前路由不需要认证，直接渲染子组件
  if (!requireAuth || !requiresAuth(currentPath)) {
    return children;
  }

  // 如果正在加载，显示加载状态
  if (loading) {
    return fallback || (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh'
      }}>
        <div>加载中...</div>
      </div>
    );
  }

  // 如果未登录，重定向到登录页
  if (!isLogin) {
    navigate('/login', { 
      replace: true,
      state: { from: currentPath }
    });
    return null;
  }

  // 已登录，渲染子组件
  return children;
};

export default ProtectedRoute;
